package com.tbit.main.controller;


import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.MachineFaultLogConstant;
import com.tbit.main.constant.WorkOrderConstant;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.LogUtil;
import com.tbit.main.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * 维修记录
 *
 * @author Leon
 * 2020年3月11日 下午9:36:51
 */
@RestController
@RequestMapping("/repairLog")
public class RepairLogController {
    @Autowired
    private RepairLogService repairLogService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private GeoreMachineService georeMachineService;
    @Autowired
    private WorkOrderFinishingService workOrderFinishingService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private MachineFaultLogService machineFaultLogService;
    @Autowired
    private MachineFaultService machineFaultService;

    /**
     * 查询
     */
    @RequestMapping("/groupByTime")
    public JsonResult groupByTime(String token, Integer accountId, String startTime, String endTime, Integer repairState,
                                  Integer machineType, @RequestParam(value = "regionId", required = false) List<Integer> regionId) {
        AccountUser accountUserToken = tokenService.getAccount(token);

        Assert.hasLength(startTime, "System.startTime.notNull");
        Assert.hasLength(endTime, "System.endTime.notNull");
        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        List<RepairLogSta> repairLogStas = repairLogService.groupByTime(accountId, accountUserToken.getAccountUserType(), accountUserToken.getAccountUserId(), startTime, endTime, regionId, repairState, machineType);

        return JsonResult.succ(repairLogStas);
    }


    /**
     * 添加
     */
    @RequestMapping("/add")
    public JsonResult add(String token, String userCode, String repairTypes, String imageIds, String remark) {
        AccountUser accountUserToken = tokenService.getAccount(token);

        Assert.hasLength(userCode, "Machine.userCode.notNull");
        Assert.hasLength(repairTypes, "RepairLog.repairType.notNull");

        if (imageIds == null) {
            imageIds = "";
        }
        if (remark == null) {
            remark = "";
        }

        /**查询设备信息*/
        Machine machine = machineService.getByUseCode(userCode);
        if (machine == null) {
            throw new BaseException("Machine.notExist");
        }
        /**设备权限判断*/
        machineService.auth(accountUserToken.getAgents(), machine.getMachineId());

        /**查询用户信息*/
        AccountUser accountUser = accountUserService.getById(accountUserToken.getAccountUserId());
        RepairLog repairLog = new RepairLog();
        repairLog.setAccountId(machine.getAccountId());
        repairLog.setAccountUserId(accountUser.getAccountUserId());
        repairLog.setAddTime(DateTimeUtil.getNowTime());
        repairLog.setAcceptTime(DateTimeUtil.getNowTime());
        repairLog.setMachineId(machine.getMachineId());
        repairLog.setMachineNO(machine.getMachineNO());
        repairLog.setUserCode(machine.getUserCode());
        repairLog.setRemark(remark);
        repairLog.setRepairState(1);
        repairLog.setRepairTypes(repairTypes);
        repairLog.setUserName(accountUser.getName());
        repairLog.setWorkOrderNO(OrderUtil.getWorkOrderNO());
        repairLog.setImageIds(imageIds);
        repairLog.setMachineType(machine.getMachineType());

        /**
         * 判断分区
         */
        GeoreMachine georeMachine = georeMachineService.getByMachineId(machine.getMachineId());
        if (georeMachine != null) {
            repairLog.setRegionId(georeMachine.getRegionId());
        }

        repairLogService.insert(repairLog);


        /***
         * 添加故障上报日志
         */
        MachineFault machineFault = machineFaultService.getByMachineId(machine.getMachineId());
        //去除掉疑似故障
        machineFault = this.checkMachineSuspectedFault(machineFault);
        MachineFaultLog machineFaultLog = new MachineFaultLog();
        machineFaultLog.setAccountId(machine.getAccountId());
        if (georeMachine != null) {
            machineFaultLog.setRegionId(georeMachine.getRegionId());
        }
        machineFaultLog.setMachineId(machine.getMachineId());
        machineFaultLog.setUserCode(machine.getUserCode());
        machineFaultLog.setAddManId(accountUserToken.getAccountUserId());
        machineFaultLog.setAddManName(accountUser.getName());
        machineFaultLog.setAddManPhone(accountUser.getPhone());
        machineFaultLog.setAddTime(DateTimeUtil.getNowTime());
        machineFaultLog.setImageIds(imageIds);
        machineFaultLog.setIntoMain(0);
        machineFaultLog.setMachineType(machine.getMachineType());
        machineFaultLog.setRemark(remark);
        machineFaultLog.setFaultType(MachineFaultLogConstant.MAINTENANCE);
        machineFaultLog.setFaults(repairTypes);
        if (machineFault != null) {
            if (machineFault.getOrderNO() != null) {
                machineFaultLog.setOrderNO(machineFault.getOrderNO());
            } else {
                machineFaultLog.setOrderNO(OrderUtil.getNO());
            }
        } else {
            machineFaultLog.setOrderNO(OrderUtil.getNO());
        }
        machineFaultLogService.insert(machineFaultLog);


        /**是否存在工单信息*/
        WorkOrderFinishing workOrderFinishing = workOrderFinishingService.getByMachineIdWorkType(machine.getMachineId(), WorkOrderConstant.workType_WX, machine.getAccountId());
        if (workOrderFinishing != null) {
            LogUtil.info("维修上报，修改工单信息:" + workOrderFinishing);
            workOrderFinishingService.updateState(workOrderFinishing.getWorkOrderId(), accountUserToken.getAccountUserId(), accountUserToken.getName(), WorkOrderConstant.state_LQ);
            workOrderService.updateState(workOrderFinishing.getWorkOrderId(), accountUserToken.getAccountUserId(), accountUserToken.getName(), repairLog.getRepairLogId(), WorkOrderConstant.state_LQ, null);
        }

        return JsonResult.succ();
    }


    /**
     * 处理
     */
    @RequestMapping("/getByTime")
    public JsonResult getByTime(Integer accountId, Integer accountUserId, String startTime, String endTime, Integer repairState, String userCode,
                                Integer machineType, @RequestParam(value = "regionId", required = false) List<Integer> regionId) {

        Assert.notNull(accountUserId, "AccountUser.id.notNull");
        Assert.hasLength(startTime, "System.startTime.notNull");
        Assert.hasLength(endTime, "System.endTime.notNull");
        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        List<RepairLog> repairLogs = repairLogService.getByTime(accountId, accountUserId, startTime, endTime, regionId, repairState, userCode, machineType);

        return JsonResult.succ(repairLogs);
    }


    /**
     * 根据id查询
     */
    @RequestMapping("/getById")
    public JsonResult getById(String token, Integer repairLogId) {
        Assert.notNull(repairLogId, "System.id.notNull");

        RepairLog repairLog = repairLogService.getById(repairLogId);

        return JsonResult.succ(repairLog);
    }

    /**
     * @description: 检查故障是否是疑似故障，如果是疑似故障则删除掉疑似故障，把正式的故障加入
     * @author: mo.shanyong
     * @date: 2025/5/13 17:07
     * @param: machineFaultInDbd
     * @return: com.tbit.main.pojo.MachineFault
     */
    private MachineFault checkMachineSuspectedFault(MachineFault machineFaultInDbd){
        //故障为空，或者不是疑似故障，则直接返回
        if (Objects.isNull(machineFaultInDbd) || !Objects.equals(machineFaultInDbd.getFrom(),4)){
            return machineFaultInDbd;
        }
        return null;
    }

}